<!DOCTYPE html>
<html xmlns:g="http://www.w3.org/1999/xhtml" xmlns:r="">
<head>
    <script>
        /* define url controllers used in javascript function */
        var GET_PROJECT_CTRL = '<g:createLink controller="Home" action="listProjects"/>';
        var GET_TEAMS_CTRL = '<g:createLink controller="Home" action="getTeams"/>';
        var GET_SPRINTS_CTRL = '<g:createLink controller="Home" action="getSprints"/>';
        var GET_USERSTORY_CTRL = '<g:createLink controller="Home" action="getUserStories"/>';
        var EDIT_USERSTORY_CTRL = '<g:createLink controller="Home" action="updateUserStory"/>';
        var DELETE_USERSTORY_CTRL = '<g:createLink controller="Home" action="deleteUserStory"/>';
        var GET_RETROSPECTIVE_CTRL = '<g:createLink controller="Home" action="showRetrospective"/>';
        var CREATE_USERSTORY_CTRL = '<g:createLink controller="Home" action="createUserStory"/>';
        var SAVE_USERSTORY_CTRL = '<g:createLink controller="Home" action="updateUserStory"/>';

        var UPDATE_RETRO_TYPE_CTRL = '<g:createLink controller="retrospectiveResult" action="updateType"/>';
        var UPDATE_RETRO_CTRL = '<g:createLink controller="retrospectiveResult" action="updateRetro"/>';
        var GET_RETRO_CTRL = '<g:createLink controller="retrospectiveResult" action="getRetro"/>';
        var DETELE_RETRO_CTRL = '<g:createLink controller="retrospectiveResult" action="delRetro"/>';
        var SHOW_RETRO_CTRL = '<g:createLink controller="retrospectiveResult" action="showRetro"/>';
        var CREATE_RETRO_CTRL = '<g:createLink controller="retrospectiveResult" action="addRetro"/>';
        var GET_CHARTDATA_CTRL = '<g:createLink controller="Home" action="getChartData"/>';

        var FIND_VIDEO_BY_SPRINT = '${createLink(controller: 'MeetingVideo', action: 'jsonFindVideoBySprint')}';
        var VIDEO_LINK_WITHOUT_FILE_NAME = '${createLink(mapping: "fileMapping", params : [location: 'meeting_video'], absolute : true) }';
    </script>
    <meta name="layout" content="template">
    <r:require modules="jquery, jQueryValidate, FlowPlayer"/>
    <link rel="stylesheet" href="${resource(dir: 'home', file: 'home.css')}">
    <link rel="stylesheet" href="${resource(dir: 'home', file: 'retro.css')}">
    <link
            href="http://fonts.googleapis.com/css?family=Reenie+Beanie:regulbvbar"
            rel="stylesheet" type="text/css">
    <script src="${resource(dir: 'home', file: 'home.js')}"></script>
    <script src="${resource(dir: 'home', file: 'retro.js')}"></script>
    <script type="text/javascript" src="${resource(dir: 'js', file: 'jquery.blockUI.js')}"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script src="${resource(dir: 'home', file: 'chart.js')}"></script>
    <title>My agile::Home page</title>
</head>
<body>
<script>
$(document)
        .ready(
        function () {
            /* burndown chart------------------------------------------------------------------*/
            function drawChartOnChangeSprint(id) {
                if (id) {
                    $('#resultChart').height("350px");
                    $.ajax({
                        url: GET_CHARTDATA_CTRL,
                        dataType: 'json',
                        data: {
                            id: id
                        },
                        beforeSend: function () {
                            $('#burndownchart').block({
                                centerY: 0,
                                css: {
                                    color: '#898585',
                                    border: '0px',
                                    backgroundColor: 'transparent'
                                },
                                message: '<img src="${resource(dir: 'images', file: 'ajax_loader_gray_32.gif')}" /><br/><b>Loading...</b>',
                                overlayCSS: {
                                    backgroundColor: '#F1F1F1'
                                }
                            });
                        },
                        complete: function () {
                            $('#burndownchart').unblock();
                        },
                        success: function (result) {
                            //console.log(result);
                            var data = drawChart(result);
                            //console.log(data[0]);
                            google.setOnLoadCallback(drawChartCallback(data[0], data[1]));
                        }
                    });
                } else {
                    $('#resultChart').height("20px");
                    $('#resultChart').html("<div>No data</div>");

                }
            }

            function drawChartCallback(data, options) {
                var chart = new google.visualization.LineChart(document.getElementById('resultChart'));
                chart.draw(data, options);
            }

            //init
            function initialDataOnPageLoad() {
                getProjects();
                var projectId = $('.main-selector [name="project"]').val();
                getTeams(projectId);
                var teamId = $('.main-selector [name="team"]').val();
                getSprints(projectId, teamId);
                var sprintId = $('.sprint-selector [name="sprint"]').val();
                getUserStories(projectId);
                getImpediments(projectId, teamId);
                drawChartOnChangeSprint(sprintId);
            }

            /* action on project selector change value */
            $(document).on('change', '.main-selector [name="project"]', function () {
                var projectId = $(this).val();

                // prevent form lost
                $('[class$="form"]').appendTo('.rest-in-peace');
                $('[class$="form"]').hide();

                getTeams(projectId);
                getUserStories(projectId);

                $('.main-selector [name="team"]').trigger('change');
                $('.sprint-selector [name="sprint"]').trigger('change');
            });

            /* action on team selector change value */
            $(document).delegate('.main-selector [name="team"]', 'change', function () {
                var projectId = $('.main-selector [name="project"]').val();
                var teamId = $(this).val();

                // prevent form lost
                $('.impediment-form').appendTo('.rest-in-peace');
                $('.impediment-form').hide();

                getSprints(projectId, teamId);
                getImpediments(projectId, teamId);

                $('.sprint-selector [name="sprint"]').trigger('change');
            });

            $(document).on('change', '.sprint-selector [name="sprint"]', function () {
                var projectId = $('.main-selector [name="project"]').val();
                var teamId = $('.main-selector [name="team"]').val();

                //burndown chart
                drawChartOnChangeSprint($('.sprint-selector [name="sprint"]').val());
            });

            $(document).delegate('.user-story-form [name="save"]', 'click', function () {
                var $form = $('.user-story-form');

                $form.validate({
                    rules: USERSTORY_RULES,
                    messages: USERSTORY_MESSAGES,
                    submitHandler: function () {
                        var userStory = getUserStoryFormData();
                        userStory.id = $('.user-story-form').parents('section.user-story').attr('id');

                        hideUserStoryForm();
                        saveUserStory(userStory);
                        resetUserStoryForm();
                    }
                });
                $form.submit();
            });

            $(document).delegate('.user-story-form [name="create"]', 'click', function () {
                var $form = $('.user-story-form');

                $form.validate({
                    rules: USERSTORY_RULES,
                    messages: USERSTORY_MESSAGES,
                    submitHandler: function () {
                        var userStory = getUserStoryFormData();

                        hideUserStoryForm();
                        createUserStory(userStory);
                        resetUserStoryForm();
                    }
                });
                $form.submit();
            });

            $(document).delegate('.user-story-form [name="cancel"]', 'click', function () {
                var $userStory = $(this).parents('section.user-story');

                $userStory.removeClass('to-do in-progress done');
                $userStory.addClass($userStory.find('div[name="status"]').text());

                resetUserStoryForm();
                hideUserStoryForm();
            });

            $(document).on('hover', '.user-story', function (event) {
                if (event.type == 'mouseenter') {
                    $(this).find('.user-story-ctrl').fadeIn();
                } else {
                    $(this).find('.user-story-ctrl').fadeOut();
                }
            });

            $('.new-user-story-btn').click(function () {
                var $form = $('.user-story-form');

                resetUserStoryForm();

                if ($form.is(':visible') && $form.parent().is('section.user-story')) {
                    hideUserStoryForm();
                    setTimeout(function () {
                        showCreateUserStoryForm();
                    }, 300);
                } else {
                    showCreateUserStoryForm();
                }
            });

            /* click on edit button in user story -------------------------------------------------------------- */
            $(document).delegate('.user-story-ctrl [name="editButton"]', 'click', function () {
                var button = $(this);
                var $userStory = $(this).parents('.user-story');
                var obj = getDataFromUserStory($userStory);

                setUserStoryForm(obj);

                if ($('.user-story-form').is(':visible')) {
                    hideUserStoryForm();
                    setTimeout(function () {
                        showEditUserStoryForm(button);
                    }, 300);
                } else {
                    showEditUserStoryForm(button);
                }
            });

            $('.user-story-form').on('change', '[name="status"]', function () {
                var $userStory = $(this).parents('section.user-story');

                $userStory.removeClass('to-do in-progress done');
                $userStory.addClass($(this).val());
            });

            /* auto load selector data at the first time ------------------------------------------------------- */
            initialDataOnPageLoad();


            /* retrospective result ---------------------------------------------------------------------------- */
            $(document).on('hover', '.impediment', function (event) {
                if (event.type == 'mouseenter') {
                    $(this).find('.impediment-ctrl').fadeIn();
                } else {
                    $(this).find('.impediment-ctrl').fadeOut();
                }
            });

            $('.new-impediment-btn').click(function () {
                var $form = $('.impediment-form');

                resetImpedimentForm();

                if ($form.is(':visible') && $form.parent().is('section.impediment')) {
                    hideImpedimentForm();
                    setTimeout(function () {
                        showCreateImpedimentForm();
                    }, 300);
                } else {
                    showCreateImpedimentForm();
                }
            });

            $(document).on('click', '.impediment-form [name="cancel"]', function () {
                resetImpedimentForm();
                hideImpedimentForm();
            });

            $(document).on('click', '.impediment-form [name="create"]', function () {
                var $form = $('.impediment-form');

                $form.validate({
                    rules: IMPEDIMENT_RULES,
                    messages: IMPEDIMENT_MESSAGES
                });
                $form.validate().settings.submitHandler = function () {
                    var obj = getImpedimentFormData();
                    createImpediment(obj);
                    hideImpedimentForm();
                };
                $form.submit();
            });

            $(document).on('click', '.impediment-form [name="save"]', function () {
                var button = $(this);
                var $form = $('.impediment-form');

                $form.validate({
                    rules: IMPEDIMENT_RULES,
                    messages: IMPEDIMENT_MESSAGES
                });
                $form.validate().settings.submitHandler = function () {
                    updateImpediment(button);
                    hideImpedimentForm();
                };
                $form.submit();
            });

            $(document).on('click', '.impediment-ctrl [name="editButton"]', function () {
                var button = $(this);
                var $impediment = $(this).parents('.impediment');
                var obj = getDataFromImpediment($impediment);

                setImpedimentForm(obj);

                if ($('.impediment-form').is(':visible')) {
                    hideImpedimentForm();
                    setTimeout(function () {
                        showEditImpedimentForm(button);
                    }, 300);
                } else {
                    showEditImpedimentForm(button);
                }
            });

            $(document).on('click', '.impediment .Unsolved', function () {
                changeImpedimentStatus($(this));
            });

            $(document).on('click', '.impediment-ctrl [name="deleteButton"]', function () {
                if (confirm("Delete this impediment?")) {
                    var $impediment = $(this).parents('.impediment')
                    deleteImpediment($impediment.attr('id'));
                    $impediment.hide(300);
                }
            });
            /* end - retrospective result ---------------------------------------------------------------------- */
        });
</script>

<div class="page-container">
    <form class="form-inline text-center main-selector">
        <select class="combo-box" name="project"></select>
        <select class="combo-box" name="team"></select>
    </form>

    <div class="row backlogs-container">
        <div class="span3 product-backlog">
            <h5 class="title">Product backlog</h5>

            <form class="form-inline user-story-filter text-center">
                <label class="checkbox">
                    <input type="checkbox" checked="checked" name="showTodo"> Todo
                </label>
                <label class="checkbox">
                    <input type="checkbox" checked="checked" name="showInProgress"> In progress
                </label>
                <label class="checkbox">
                    <input type="checkbox" checked="checked" name="showDone"> Done
                </label>
            </form>

            <hr/>

            <div class="backlog-ctrl">
                <a class="btn btn-mini btn-info new-user-story-btn"><i class="icon-plus icon-white"></i> New</a>
            </div>

            <section class="user-stories"></section>
        </div>

        <div class="span6 sprint-backlog" style="padding: 10px;">
            <h5 class="title">Sprint backlog</h5>

            <form class="form-inline text-center sprint-selector">
                <select class="combo-box" name="sprint" id="sprintObj"></select> <%-- burndown chart id="sprintObj"--%>
            </form>

            <div class="text-center sprint-content">
            	<div class="row">
	            	<div class="span4 text-left">
	            		<select name="meeting-video" id="meeting-video">
	            			
	            		</select>
	            	</div>
            	</div>
                <div id="daily-meeting-video" class="daily-metting-video">

                </div>
            
                <div class="chart">
                    <div id="burndownchart" class="sprint-content" style="margin-top: 45px">
                        <div id="resultChart"></div>
                    </div>
                    <!-- End Burndown chart -->
                </div>
            </div>
        </div>

        <div class="span3 impediment-backlog">
            <h5 class="title">Impediment backlog</h5>

            <div class="backlog-ctrl">
                <a class="btn btn-mini btn-info new-impediment-btn"><i class="icon-plus icon-white"></i>
                    New</a>
            </div>

            <section class="impediments"></section>
        </div>
    </div>

    <div class="hide rest-in-peace">
        <form class="hide user-story-form">
            <fieldset>
                <div class="control-group">
                    <div class="controls">
                        <input name="name" type="text" placeholder="Name" class="input-medium">
                    </div>
                </div>

                <div class="control-group">
                    <div class="controls">
                        <textarea name="description" rows="5" class="input-large"></textarea>
                    </div>
                </div>

                <div class="control-group">
                    <div class="controls">
                        <input name="value" type="number" placeholder="Value" class="input-small">
                    </div>
                </div>

                <div class="control-group">
                    <div class="controls">
                        <select name="status" class="input-medium">
                            <option value="to-do">To do</option>
                            <option value="in-progress">In progress</option>
                            <option value="done" selected>Done</option>
                        </select>
                    </div>
                </div>

                <div class="control-group hide">
                    <div class="controls">
                        <input name="project" type="hidden"/>
                    </div>
                </div>

                <div class="control-group">
                    <div class="controls">
                        <button type="button" name="create" class="btn btn-mini btn-info">Create</button>
                        <button type="button" name="save" class="btn btn-mini btn-info">Save</button>
                        <button type="button" name="cancel" class="btn btn-mini btn-info">Cancel</button>
                    </div>
                </div>
            </fieldset>
        </form>

        <form class="hide impediment-form">
            <fieldset>
                <div class="control-group">
                    <div class="control-label" c="descLabel">New Impediment</div>
                    <div class="controls">
                        <textarea name="description" rows="5" class="input-large"></textarea>
                    </div>
                </div>
                <div class="control-group">
                    <div class="controls">
                        <button type="button" name="create" type="submit" class="btn btn-mini btn-info">Create</button>
                        <button type="button" name="save" type="submit" class="btn btn-mini btn-info">Save</button>
                        <button type="button" name="cancel" class="btn btn-mini btn-info">Cancel</button>
                    </div>
                </div>
            </fieldset>
        </form>

        <section class="user-story">
            <div class="content">
                <div class="hide user-story-ctrl">
                    <i class="icon-edit" name="editButton"></i> <i class="icon-remove"></i>
                </div>

                <strong>
                    <div name="name"></div>
                </strong>

                <div name="description"></div>
                <div>Business value: <strong name="value"></strong></div>
                <div class="hide" name="status"></div>
            </div>
        </section>

        <section class="impediment">
            <div class="content">
                <div class="hide impediment-ctrl">
                    <i class="icon-edit" name="editButton"></i> <i class="icon-remove" name="deleteButton"></i>
                </div>
                <div><strong><span name="owner"></span></strong> <span name="date"></span></div>
                <div name="description"></div>
                <div name="status"></div>
            </div>
        </section>
    </div>
</div>
<script type="text/javascript">google.load("visualization", "1", {packages: ["corechart"]});</script>
<script type="text/javascript">
	jQuery(document).ready(function($) {
		//call ajax for loading video
		ajaxGetVideoBySprint($('#sprintObj').val());
		
		function ajaxGetVideoBySprint(sprintID) {
			$.get(FIND_VIDEO_BY_SPRINT,{sprintID : sprintID},function(data) {
				if(data.meetingVideos) {
					$("#meeting-video").empty();
					$.each(data.meetingVideos, function(index, meetingVideo) {
						var meetingDate = new Date(meetingVideo.meetingDate).format("yyyy-mm-dd");
						$("#meeting-video").show().append("<option id='"+meetingVideo.id+"' value='"+meetingVideo.videoFileName+"'>"+meetingDate+"</option>");
						$("#meeting-video").trigger("change");			
					});
				} else {
					$("#meeting-video").hide();
					$("#daily-meeting-video").empty().append("<div class='alert alert-warn'>No Meeting Video Uploaded</div>");
				}
			});
		}

		function showVideoByDate(fileName) {
			var videoLink = VIDEO_LINK_WITHOUT_FILE_NAME+"/"+fileName;
			var flowplayerEl = $("<div class='flowplayer'></div>");
			var videoEl = $("<video preload='none'><source type='video/mp4' src='"+videoLink+"'></source></video>");
			flowplayerEl.append(videoEl);
			$("#daily-meeting-video").empty().append(flowplayerEl);
			$(".flowplayer").flowplayer(); // init flow player
		}

		// Event listener
		$('#meeting-video').on("change", function() {
			if($(this).val() != '-1') {
				showVideoByDate($(this).val());
			}
		});

		$("#sprintObj").on("change", function() {
			ajaxGetVideoBySprint($(this).val());
		});

		$("[name='project']").on('change', function() {
			ajaxGetVideoBySprint($(this).val());
		});
	});
</script>
</body>
</html>
